using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ERP.OrderManage;
using ERP.OrderManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 销售送货订单控制器
    /// </summary>
    public class SaleSendOrderController : Controller
    {
        private readonly ISaleSendOrderService _saleSendOrderService;
        private readonly ILogger<SaleSendOrderController> _logger;

        public SaleSendOrderController(
            ISaleSendOrderService saleSendOrderService,
            ILogger<SaleSendOrderController> logger)
        {
            _saleSendOrderService = saleSendOrderService;
            _logger = logger;
        }

        /// <summary>
        /// 销售送货订单管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 创建销售送货订单页面
        /// </summary>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 销售送货订单编辑页面
        /// </summary>
        public IActionResult Edit(int? id)
        {
            ViewBag.Id = id;
            return View();
        }

        /// <summary>
        /// 获取销售送货订单列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSaleSendOrders(GetSaleSendOrderInputDto input)
        {
            try
            {
                _logger.LogInformation("获取销售送货订单列表，参数: {@Input}", input);
                
                // 处理排序字段，将OrderStatus替换为State
                if (!string.IsNullOrWhiteSpace(input.Sorting) && input.Sorting.Contains("OrderStatus"))
                {
                    input.Sorting = input.Sorting.Replace("OrderStatus", "State");
                }
                
                var result = await _saleSendOrderService.GetListAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取销售送货订单列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<SaleSendOrderDto>()
                });
            }
        }

        /// <summary>
        /// 获取销售送货单
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSaleSendOrder(int id)
        {
            try
            {
                var order = await _saleSendOrderService.GetAsync(id);
                return Json(new { code = 0, data = order, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取销售送货单失败，ID: {Id}", id);
                return Json(new { code = 500, msg = "获取失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 创建销售送货订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateSaleSendOrder(CreateSaleSendOrderDto input)
        {
            try
            {
 


                
                if (!ModelState.IsValid)
                {
                    var errorMessages = string.Join("; ", ModelState.Values
                        .SelectMany(x => x.Errors)
                        .Select(x => x.ErrorMessage));
                    
                    _logger.LogWarning("创建销售送货订单验证失败：{ErrorMessages}", errorMessages);
                    
                    return Json(new
                    {
                        code = 400,
                        msg = errorMessages
                    });
                }


                // 确保日期格式正确
                if (input.OrderDate.Kind == DateTimeKind.Unspecified)
                {
                    input.OrderDate = DateTime.SpecifyKind(input.OrderDate, DateTimeKind.Local);
                }

                var order = await _saleSendOrderService.CreateAsync(input);

                // 构造标准的成功响应
                _logger.LogInformation("创建销售送货订单成功，ID: {Id}", order.Id);
                
                // 如果是表单提交，重定向到编辑页面
                if (!Request.Headers["Content-Type"].ToString().Contains("json"))
                {
                    return RedirectToAction("Edit", new { id = order.Id });
                }
                
                return Json(new
                {
                    code = 0,
                    msg = "创建成功",
                    success = true,
                    data = new {
                        id = order.Id,
                        orderCode = order.OrderCode,
                        customerName = order.CustomerName,
                        orderDate = order.OrderDate.ToString("yyyy-MM-dd")
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建销售送货订单失败");
                
                // 如果是表单提交，返回错误视图
                if (!Request.Headers["Content-Type"].ToString().Contains("json"))
                {
                    TempData["ErrorMessage"] = "创建失败: " + ex.Message;
                    return RedirectToAction("Index");
                }
                
                return Json(new
                {
                    code = 500,
                    msg = "创建失败: " + ex.Message,
                    success = false,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 更新销售送货订单
        /// </summary>
        [HttpPut]
        [HttpPost] // 同时支持POST和PUT
        public async Task<IActionResult> UpdateSaleSendOrder(int id, UpdateSaleSendOrderDto input)
        {
            try
            {
                _logger.LogInformation("更新销售送货订单开始，ID: {Id}", id);
                
                // 记录表单字段
                foreach (var key in Request.Form.Keys)
                {
                    _logger.LogInformation("表单字段 {Key} = {Value}", key, Request.Form[key]);
                }
                
                // 确保日期格式正确
                if (input.OrderDate.Kind == DateTimeKind.Unspecified)
                {
                    input.OrderDate = DateTime.SpecifyKind(input.OrderDate, DateTimeKind.Local);
                }
                
                _logger.LogInformation("更新销售送货订单，ID: {Id}, 参数: {@Input}", id, input);
                var order = await _saleSendOrderService.UpdateAsync(id, input);

                _logger.LogInformation("更新销售送货订单成功，ID: {Id}", id);
                
                // 如果是表单提交，重定向到编辑页面
                if (!Request.Headers["Content-Type"].ToString().Contains("json"))
                {
                    return RedirectToAction("Edit", new { id = id });
                }
                
                return Json(new
                {
                    code = 0,
                    msg = "更新成功",
                    success = true,
                    data = new {
                        id = order.Id,
                        orderCode = order.OrderCode,
                        customerName = order.CustomerName,
                        orderDate = order.OrderDate.ToString("yyyy-MM-dd")
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新销售送货订单失败，ID: {Id}", id);
                
                // 如果是表单提交，返回错误视图
                if (!Request.Headers["Content-Type"].ToString().Contains("json"))
                {
                    TempData["ErrorMessage"] = "更新失败: " + ex.Message;
                    return RedirectToAction("Edit", new { id = id });
                }
                
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    success = false,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 删除销售送货订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteSaleSendOrder(int id)
        {
            try
            {
                _logger.LogInformation("删除销售送货订单，ID: {Id}", id);
                await _saleSendOrderService.DeleteAsync(id);

                return Json(new
                {
                    code = 0,
                    msg = "删除成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除销售送货订单失败，ID: {Id}", id);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取订单编码
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateOrderCode()
        {
            try
            {
                var code = await _saleSendOrderService.GenerateOrderCodeAsync();
                return Json(new
                {
                    success = true,
                    code = code
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成订单编码失败");
                return Json(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 添加明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddOrderDetail([FromBody] ERP.OrderManage.Dtos.CreateSaleSendOrderDetailDto input)
        {
            try
            {
                // 确保amountDECIMAL和amountVARCHAR值保持一致
                input.AmountDECIMAL = input.AmountVARCHAR;
                
                var detail = await _saleSendOrderService.CreateOrderDetailAsync(input);
                return Json(new { code = 0, data = detail, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加销售送货单明细失败");
                return Json(new { code = 500, msg = "添加失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 更新订单明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateOrderDetail(int detailId, [FromBody] UpdateSaleSendOrderDetailDto input)
        {
            try
            {
                _logger.LogInformation("更新销售送货订单明细，ID: {Id}, 参数: {@Input}", detailId, input);
                var detail = await _saleSendOrderService.UpdateOrderDetailAsync(detailId, input);

                return Json(new
                {
                    code = 0,
                    msg = "更新成功",
                    data = detail
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新销售送货订单明细失败，ID: {Id}", detailId);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 删除订单明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteOrderDetail(int detailId)
        {
            try
            {
                _logger.LogInformation("删除销售送货订单明细，ID: {Id}", detailId);
                await _saleSendOrderService.DeleteOrderDetailAsync(detailId);

                return Json(new
                {
                    code = 0,
                    msg = "删除成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除销售送货订单明细失败，ID: {Id}", detailId);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取订单明细列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetOrderDetails(int orderId)
        {
            try
            {
                _logger.LogInformation("获取销售送货订单明细列表，订单ID: {OrderId}", orderId);
                var details = await _saleSendOrderService.GetOrderDetailsAsync(orderId);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    data = details
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取销售送货订单明细列表失败，订单ID: {OrderId}", orderId);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new List<SaleSendOrderDetailDto>()
                });
            }
        }

        /// <summary>
        /// 确认订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ConfirmOrder(int id)
        {
            try
            {
                _logger.LogInformation("确认销售送货订单，ID: {Id}", id);
                var order = await _saleSendOrderService.ConfirmOrderAsync(id);

                return Json(new
                {
                    code = 0,
                    msg = "确认成功",
                    data = order
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "确认销售送货订单失败，ID: {Id}", id);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 提交审批
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SubmitForApproval(int id)
        {
            try
            {
                _logger.LogInformation("提交销售送货订单审批，ID: {Id}", id);
                var order = await _saleSendOrderService.SubmitForApprovalAsync(id);

                return Json(new
                {
                    code = 0,
                    msg = "提交审批成功",
                    data = order
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提交销售送货订单审批失败，ID: {Id}", id);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 审批通过
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ApproveOrder(int id)
        {
            try
            {
                _logger.LogInformation("审批通过销售送货订单，ID: {Id}", id);
                var order = await _saleSendOrderService.ApproveOrderAsync(id);

                return Json(new
                {
                    code = 0,
                    msg = "审批通过成功",
                    data = order
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审批通过销售送货订单失败，ID: {Id}", id);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 审批拒绝
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> RejectOrder(int id)
        {
            try
            {
                _logger.LogInformation("审批拒绝销售送货订单，ID: {Id}", id);
                var order = await _saleSendOrderService.RejectOrderAsync(id);

                return Json(new
                {
                    code = 0,
                    msg = "审批拒绝成功",
                    data = order
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审批拒绝销售送货订单失败，ID: {Id}", id);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 导出订单
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportOrders(GetSaleSendOrderInputDto input)
        {
            try
            {
                _logger.LogInformation("导出销售送货订单，参数: {@Input}", input);
                var fileData = await _saleSendOrderService.ExportAsync(input);

                return File(fileData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "销售送货订单导出.xlsx");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出销售送货订单失败");
                return Content("导出失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取产品选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProducts(GetProductSelectInputDto input)
        {
            try
            {
                var result = await _saleSendOrderService.GetProductsForSelectAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取产品选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<ProductSelectDto>()
                });
            }
        }

        /// <summary>
        /// 获取客户选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomers(GetCustomerSelectInputDto input)
        {
            try
            {
                var result = await _saleSendOrderService.GetCustomersForSelectAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取客户选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<CustomerSelectDto>()
                });
            }
        }

        /// <summary>
        /// 获取仓库选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWarehouses()
        {
            try
            {
                var warehouses = await _saleSendOrderService.GetWarehousesForSelectAsync();

                return Json(new
                {
                    code = 0,
                    msg = "",
                    data = warehouses
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new List<WarehouseSelectDto>()
                });
            }
        }

        /// <summary>
        /// 从销售订单导入数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ImportFromSaleOrder(int saleOrderId, int saleSendOrderId)
        {
            try
            {
                _logger.LogInformation("从销售订单导入数据，销售订单ID: {SaleOrderId}, 送货订单ID: {SendOrderId}", saleOrderId, saleSendOrderId);
                var details = await _saleSendOrderService.ImportFromSaleOrderAsync(saleOrderId, saleSendOrderId);

                return Json(new
                {
                    code = 0,
                    msg = "导入成功",
                    data = details
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从销售订单导入数据失败，销售订单ID: {SaleOrderId}, 送货订单ID: {SendOrderId}", saleOrderId, saleSendOrderId);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new { }
                });
            }
        }

        /// <summary>
        /// 产品选择页面
        /// </summary>
        public IActionResult ProductSelect()
        {
            return View();
        }

        /// <summary>
        /// 客户选择页面
        /// </summary>
        public IActionResult CustomerSelect()
        {
            return View();
        }

        /// <summary>
        /// 仓库选择页面
        /// </summary>
        public IActionResult WarehouseSelect()
        {
            return View();
        }

        /// <summary>
        /// 销售订单选择页面
        /// </summary>
        public IActionResult SaleOrderSelect()
        {
            return View();
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> TestDatabase()
        {
            try
            {
                // 测试直接操作数据库
                var result = await _saleSendOrderService.GetWarehousesForSelectAsync();
                return Json(new { code = 0, data = result, msg = "数据库操作测试成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库测试失败");
                return Json(new { code = 500, msg = "数据库测试失败: " + ex.Message });
            }
        }
    }
}